package com.globant.dao;

import java.util.ArrayList;
import java.util.List;

import android.app.Application;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

import com.globant.domain.PlaceBean;
import com.globant.placemaps.PlaceContentProvider;

public class PlaceDao {
	
	private Application service;
	
	public PlaceDao(Application main) {
		service = main;
	}
	
	public void insert(PlaceBean place) {
		ContentValues values = new ContentValues();
		 
			
		values.put(PlaceBean.COL_DESCRIPTION, place.getDescription());
		values.put(PlaceBean.COL_LATITUDE, place.getLatitude());
		values.put(PlaceBean.COL_LONGITUDE, place.getLongitude());
		values.put(PlaceBean.COL_NAME, place.getName());
		
		ContentResolver cr = service.getContentResolver();
		
		cr.insert(PlaceContentProvider.CONTENT_URI, values);

	}
	
	public List<PlaceBean> obtainResults() {
        String[] projection = new String[] {
        		PlaceBean.COL_DESCRIPTION,
        		PlaceBean.COL_LATITUDE,
        		PlaceBean.COL_LONGITUDE,
        		PlaceBean.COL_NAME};

        Uri tweetsUri =  PlaceContentProvider.CONTENT_URI;

        ContentResolver cr = service.getContentResolver();
        
        Cursor cur = cr.query(tweetsUri,
                                 projection,
                                 null,
                                 null,
                                 null);
        
        List<PlaceBean> places = new ArrayList<PlaceBean>();
        
		if (cur.moveToFirst()) {            
            int colName = cur.getColumnIndex(PlaceBean.COL_NAME); 
            int colDescription = cur.getColumnIndex(PlaceBean.COL_DESCRIPTION);
            int colLatitude = cur.getColumnIndex(PlaceBean.COL_LATITUDE);
            int colLongitude = cur.getColumnIndex(PlaceBean.COL_LONGITUDE);
            
			do {
				PlaceBean place = new PlaceBean();
				place.setDescription(cur.getString(colDescription));
				place.setLatitude(cur.getInt(colLatitude));
				place.setLongitude(cur.getInt(colLongitude));
				place.setName(cur.getString(colName));
				
				places.add(place);
            } while (cur.moveToNext());
        }
		
		return places;
	}
	
}
